import React from 'react';
import { Cascader, Spin, Typography } from 'antd';
import { useDictList } from '@/pages/Organization/Job/hooks';
import { getPostListByCondition } from '@/services/flowMine/apply';

const Position = ({ onChange, recordKey, value: postRows }) => {
    const [options, setOptions] = React.useState([]);
    const [initLoading, setInitLoading] = React.useState(false);
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const [loading, postList = [], childPostList, fetchDictList] = useDictList({ code: 'positionType' });
    const rowIndex = postRows.findIndex(item => item.key === recordKey);
    const rowValue = postRows[rowIndex];

    // 模糊查询请求职位接口
    const fetchPostList = async query => {
        const { data: datalist = [] } = (await getPostListByCondition(query)) || {};
        return datalist;
    };

    // 格式化级联默认值
    const getCascaderValue = () => {
        const { level1, level2, value } = rowValue;
        if (level1 && level2 && value) {
            return [level1, level2, value];
        }
        return null;
    };
    // 显示数据过长hover上显示全部数据
    const getCascaderName = () => {
        const { level1, level2, value } = rowValue;
        if (level1 && level2 && value && options.length > 0) {
            const level1Data = options.filter(item => item.value === level1);
            const level2Data = ([...level1Data].pop().children || []).filter(item => item.value === level2);
            const valueData = ([...level2Data].pop().children || []).filter(item => item.value === value);
            return `${level1Data[0].label}/${level2Data[0].label}/${valueData[0].label}`;
        }
        return null;
    };
    // onChange设置表单值
    const replaceValueByKey = replacement => {
        onChange([...postRows.slice(0, rowIndex), { ...rowValue, ...replacement }, ...postRows.slice(rowIndex + 1)]);
    };

    // 格式化职位类别
    const formatDictData = (list, extra = {}) =>
        list.map(item => ({
            value: item.dictValue,
            label: item.dictName,
            remark: item.remark,
            isLeaf: false,
            ...extra,
            ...(item.children ? { children: item.children } : {})
        }));

    // 格式化职位列表
    const formatPostData = list =>
        list.map(item => ({
            label: item.postName,
            value: item.id,
            isLeaf: true,
            level: 3
        }));

    // 获取所有的职位级联数据
    const fetchCascaderData = async () => {
        const { level1, level2 } = rowValue;
        const match = postList.find(item => Number(item.dictValue) === Number(level1));
        const postListLevel2 = await fetchDictList({ code: match.remark, type: 'child' });
        const postListLevel3 = await fetchPostList({ secondPositionCode: level2 });
        return [postListLevel2, postListLevel3];
    };

    // 初始化级联数据
    const initComposePost = async () => {
        const { level1, level2 } = rowValue;
        setInitLoading(true);
        const [postListLevel2, postListLevel3] = await fetchCascaderData();
        setInitLoading(false);

        const composePostListLevel2 = postListLevel2.map(item => ({
            ...item,
            ...(Number(item.dictValue) === Number(level2) ? { children: formatPostData(postListLevel3) } : {})
        }));

        const composePostList = postList.map(item => ({
            ...item,
            ...(Number(item.dictValue) === Number(level1)
                ? { children: formatDictData(composePostListLevel2, { level: 2 }) }
                : {})
        }));

        setOptions([...formatDictData(composePostList, { level: 1 })]);
    };

    React.useEffect(() => {
        // 编辑，rowValue是传入的prop，先与postList
        if (postList.length && rowValue.level1 && rowValue.level2) {
            const init = async () => {
                await initComposePost();
            };
            init();
            return;
        }
        // 新建
        setOptions(formatDictData(postList, { level: 1 }));
    }, [postList]);

    const handelChange = (value, selectedOptions) => {
        const lastNode = [...selectedOptions].pop();
        if (!lastNode) {
            // 清空
            replaceValueByKey({
                key: recordKey,
                ...{
                    level1: undefined,
                    level2: undefined,
                    value: undefined
                }
            });
            return;
        }
        const replacement = {};
        const keyMap = {
            1: 'level1',
            2: 'level2',
            3: 'value'
        };
        replacement[keyMap[lastNode.level]] = lastNode.value;
        // 重置掉下一级
        if (lastNode.level < 3) {
            replacement.value = undefined;
        }
        if (lastNode.level < 2) {
            replacement.level2 = undefined;
        }
        replaceValueByKey({ key: recordKey, ...replacement });
    };

    const loadData = async selectedOptions => {
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;
        if (targetOption.level === 1) {
            const datalist = await fetchDictList({ code: targetOption.remark, type: 'child' });
            targetOption.children = formatDictData(datalist, { level: 2 });
        }
        if (targetOption.level === 2) {
            const datalist = await fetchPostList({ secondPositionCode: targetOption.value });
            targetOption.children = formatPostData(datalist);
        }
        targetOption.loading = false;
        setOptions([...options]);
    };

    return (
        <div>
            <Spin spinning={initLoading}>
                <Typography.Text title={getCascaderName()} ellipsis>
                    <Cascader
                        value={getCascaderValue()}
                        options={options}
                        loadData={loadData}
                        onChange={handelChange}
                        changeOnSelect
                        placeholder="请选择"
                        allowClear={false}
                        style={{ width: '350px' }}
                        disabled={!!rowValue.isRelationToEmployee}
                    />
                </Typography.Text>
            </Spin>
        </div>
    );
};

export default Position;
